package com.ccrfid.rmc6.util;

import com.bedatadriven.jackson.datatype.jts.JtsModule;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.TimeZone;

public enum JsonUtil {
    INSTANCE;
    private ObjectMapper objectMapper;

    JsonUtil() {
        objectMapper = new ObjectMapper();
        //设置时间序列化格式
        objectMapper.setTimeZone(TimeZone.getDefault());
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        //注册Point/Polygon类型的序列化器
        objectMapper.registerModule(new JtsModule());
        //
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    }

    public <T> T readValue(String content, Class<T> valueType) {
        try {
            return objectMapper.readValue(content, valueType);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public <T> T readValue(String content, TypeReference<T> valueTypeRef) {
        try {
            return objectMapper.readValue(content, valueTypeRef);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public <T> T treeToValue(JsonNode jsonNode, Class<T> valueType) {
        try {
            return objectMapper.treeToValue(jsonNode, valueType);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
        return null;
    }

    public String writeValueAsString(Object o) {
        try {
            return objectMapper.writeValueAsString(o);
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        return "";
    }
}
